#!/bin/bash
# Get all the translation strings for this application.
cd /u/cem/cdc/web
#Colours
NC='\033[0m' # No Color
Red='\033[0;31m'
LightRed='\033[1;31m'
Purple='\033[0;35m'
Blue='\033[0;34m'
LightBlue='\033[1;34m'
Green='\033[0;32m'

transGrepFile="/u/tmp/transGrep.txt"
translationFile="/u/tmp/translations.txt"

#Default values
displayLocations=0 #By default don't show file locations
searchType="-f" #Default Search type
returnType="-n" #Default Output type
fileParam=""
scriptName=`basename $0`
showSearchedFiles=0
all=""
clear && printf '\033[3J' #Clear the screen

function execute {
  echo "Processing........"
  if [[ "$searchType" == "-f" ]]; then
    #Loop through all the files
    for file in $fileParam
    do
      #Check if file exists
      if [ ! -f $file ]; then
        filename=`basename $file`
        excludes="$excludes --exclude='$filename'" #Append filenames to exlcude
        filePath=$(find -name "$filename") #Find filepath to file
        filePath=${filePath:2} #Remove ./ from file path
      else
        filePath="$file"
        filename=`basename $file`
        excludes="$excludes --exclude='$filename'" #Append filenames to exlcude
      fi
      filesToGrep="$filesToGrep $filePath" #Append file paths to includes
    done

    grep -rn "_(" $filesToGrep > "$transGrepFile"
  else
    fileParam="$(echo -e "${fileParam}" | tr -d '[[:space:]]')" #Remove spaces
    if [[ $showSearchedFiles -eq 1 ]]; then
      showSearchedFiles=0
      echo -e "${Purple}-------------------------------------------${NC}";
      echo -e "Files being searched${NC}";
      grep -rnl --include="*$fileParam*" --exclude="*.swp" --exclude="*.old" \
            "\$Id" *
      echo -e "${Purple}-------------------------------------------${NC}";
    fi
    grep -rh --include="*$fileParam*" --exclude="*.swp" "_(" * >"$transGrepFile"
  fi

  allTrans=""
  #Read the translation grep file
  while read match
  do
    count=$(grep -o "_(" <<< "$match" | wc -l) #Count translation on this line

    #For each translation get the string
    for (( c=1; c<=$count; c++ ))
    do
      #Get the translated string
      output=$(sed -rn 's/.*_\((.+).*/\1/p' <<< "$match" )

      #Replace single+double quotes with dots
      patt=$(echo "$output"|tr "\"\'" ".")
      match=$(sed -e s@"$patt"@@ <<< "$match" ) #Remove matched string from line
      output="$( cut -d ')' -f 1 <<< "$output" )"; #Remove trailing characters
      echo "$output" >> "$translationFile" # Append to file
    done
  done < "$transGrepFile"

  if [[ $returnType == "-a" ]]; then
    #Output all of the translations
    echo -e "${Green} $func ***  ALL TRANSLATIONS *** ${NC}";
    cat "$translationFile"
  elif [[ $returnType == "-c" ]]; then
    #Display a count of each translation
    echo -e "${Green} $func ***  TRANSLATION COUNT *** ${NC}";
    sort "$translationFile" | uniq -c;
  else
    echo -e "${Green} $func *********  NEW  TRANSLATIONS ********* ${NC}";
    #Lookup the translations to see if they are used elsewhere
    sort "$translationFile" | while read line;
    do
      if [[ "$searchType" == "-f" ]]; then
        #Replace single+double quotes with dots
        patt=$(echo "$line"|tr "\"\'" ".")
        patt="'_($patt'"
        #Search for translation, exclude the application they are defined in
        eval grep -rnq "$excludes" --exclude-dir="free" --exclude="*.swp" "$patt" *
      else
        patt="_($line"
        #Replace single+double quotes with dots
        patt=$(echo "$patt"|tr "\"\'" ".")
        #Search for translation, exclude the application they are defined in
        grep -rnq --exclude-dir="free" --exclude="*.swp" --exclude="*$fileParam*" "$patt" *
      fi

      #Check exit code of grep 1=No Matches, Prevent duplicates matches
      if [[ "$?" -eq 1 ]] && [[ $all != *"$line"* ]]; then
        all="$all $line" #Append row variable to all
        echo -e "${Blue}$line ${NC}";
        if [[ $displayLocations -eq 1 ]]; then
          patt=$(echo "$patt"|tr -d "\'" ) #Remove single quotes
          grep -rn --exclude="*.swp" "$patt" * | while read newTrans;
          do
            IFS=':' read -ra location <<< "$newTrans" #Split string on ':'
            echo -e "   ${Purple}${location[0]}:${Green}${location[1]}${NC}";
          done
        fi
      fi
    done
  fi
}

function helper {
  echo -e "${Purple}------------------------------------------------------${NC}"
  echo -e " Get translation strings for the specified files"
  echo -e " v1.4"
  echo -e "${Purple}------------------------------------------------------${NC}"
  echo -e "  $scriptName [Type] [Return] [Files]"
  echo -e "   [Type]  => Type of files to search"
  echo -e "               ${Purple}-f${NC}  Filenames - Search only these"\
                          "files(Default)"
  echo -e "               ${Purple}-p${NC}  File Prefix - Search all file"\
                          "that contain this text"
  echo -e "   [Return]=> Type of information to return"
  echo -e "               ${Purple}-a${NC} => List all translations"
  echo -e "               ${Purple}-c${NC} => Count occurrences of translation"
  echo -e "               ${Purple}-n${NC} => List New translations(Default)"
  echo -e "   [opts]  => Optional arguments"
  echo -e "               ${Purple}-d${NC} => List files that were checked"
  echo -e "               ${Purple}-l${NC} => Show translation locations"
  echo -e "    [Files]   => List of files, separated by space"
  echo -e "  Examples"
  echo -e "  $scriptName acc_permiss_aj.php acc_permiss.php acc_permiss.js "
  echo -e "  $scriptName -p acc_ "
  echo -e "  $scriptName -p -c acc_ "
  echo -e "  $scriptName -f -n acc_permiss_aj.php acc_permiss.php"
}

#Get Parameters
for arg in "$@"
do
  if [[ "$arg" == *"?"* ]] || [[ "$arg" == *"help"* ]]; then
      helper
      exit
  fi

  case "$arg" in
    -n|-a|-c)
      returnType="$arg"
    ;;
    -l)
      displayLocations=1
    ;;
    -d)
      showSearchedFiles=1
    ;;
    -p|-f)
      searchType="$arg"
    ;;
    *)
      fileParam="$fileParam $arg"
    ;;
  esac
done

if [[ "$searchType" == *"?"* ]] || [[ "$searchType" == *"help"* ]]; then
    helper
elif [[ "$fileParam" == "" ]]; then
  echo -e "${Red}Missing parameter !!${NC}"
  helper
elif [[ "$searchType" != "-p" ]] && [[ "$searchType" != "-f" ]]; then
  echo -e "${Red}Invalid Parameter !!${NC}"
  helper
else
  execute $searchType $fileParam $returnType
  rm -f "$transGrepFile";
  rm -f "$translationFile";
fi

